package com.myopen.base;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.myopen.config.ConstConfig;
import com.myopen.model.FileInfo;
import com.myopen.model.Website;

public class BaseController extends Controller{
	
	/**
	 * 后台获取通用的查询分页参数
	 * @return
	 */
	public Record getSearchRecord(){
		
		Record record=new Record();
		
		Integer pageNumber=getParaToInt("page");
		if(pageNumber==null){
			pageNumber=1;
		}
		Integer pageSize=getParaToInt("limit");
		if(pageSize==null){
			pageSize=10;
		}
		if(pageSize>500){
			pageSize=500;//防止有人调用数据，每页最多500条数据
		}
		
		record.set("pageNumber", pageNumber);
		record.set("pageSize", pageSize);
		
		return record;
	}
	
	public Record getAdminUser(){
		return getSessionAttr(ConstConfig.SESSION_ADMIN_USER);
	}
	
	public Record getMyWebsite() {
		Record website=(Record)getSession().getAttribute(ConstConfig.SESSION_WEBSIT);
		if(website==null) {
			Record user=getAdminUser();//当cms用户从后台维护信息的时候，需要这样查询一下，因为可能没有做域名匹配
			website=Website.dao.getMyWebsite(user.getStr("id"));
		}
		
		return website;
	}
	
	public UploadFile uploadFile(String fileParam){
		UploadFile uploadFile=getFile(fileParam);
		if(uploadFile==null){
			return null;
		}
		return uploadFile;
	}
	
	public List<UploadFile> uploadFiles(String fileParam){
		List<UploadFile> uploadFiles=getFiles();
		return uploadFiles;
	}
	
	public FileInfo addFile(String fileParam,String userId){
		UploadFile uploadFile=uploadFile(fileParam);
		if(uploadFile==null){
			return null;
		}
		FileInfo fileInfo=FileInfo.dao.add(uploadFile,userId);
		return fileInfo;
	}
	
	public List<FileInfo> addFiles(String fileParam,String userId){
		List<UploadFile> uploadFiles=uploadFiles(fileParam);
		List<FileInfo> fileInfos=new ArrayList<>();
		for (UploadFile uploadFile : uploadFiles) {
			FileInfo fileInfo=FileInfo.dao.add(uploadFile, userId);
			fileInfos.add(fileInfo);
		}
		
		return fileInfos;
	}
	
	
}
